package com.lucy.nepu.module.tmaterial.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.nepu.loader.PeriodLoader;
import com.lucy.nepu.module.taward.lib.TAwardDictService;
import com.lucy.nepu.module.taward.params.TAwardQueryParams;
import com.lucy.nepu.module.tmaterial.entity.TMaterial;
import com.lucy.nepu.module.tmaterial.lib.TMaterialDict;
import com.lucy.nepu.module.tmaterial.lib.TMaterialDictService;
import com.lucy.nepu.module.tmaterial.params.TMaterialCreateParams;
import com.lucy.nepu.module.tmaterial.params.TMaterialUpdateParams;
import com.lucy.nepu.module.tmaterial.service.TMaterialService;
import com.lucy.nepu.utils.ValidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("nepu")
@Api(tags = "横向课题")
public class TMaterialController {

    @Autowired
    TMaterialService service;

    @Autowired
    TMaterialDictService dictService;

    @Autowired
    PeriodLoader periodLoader;

//    @PostMapping("books/storage")
//    @FormLock(lockKey = "BOOK_STORE",needLogin = true)
//    @ApiOperation(value = "暂存记录",notes = "")
//    public ResponseDTO<Object> setStorage(@RequestBody NepuBookAddDTO dto){
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<Object> dictOp = dictServiceCtl.getById(dto.getBookDictId(),ResearchTypeConst.BOOK);
//        if (!dictOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        }
//        NepuBookDict dict = (NepuBookDict) dictOp.get();
//        String bookGroup = dict.getBookGroup();
//        NepuDraft draft = new NepuDraft();
//        draft.setFormId(ResearchTypeConst.BOOK+bookGroup);
//        draft.setStatus(1);
//        draft.setUserId(userId);
//        draft.setFormJsonStr(JsonUtil.obj2String(dto));
//        return ResponseDTO.succData(draftService.saveOne(draft));
//    }
//
//    @GetMapping("books/storage")
//    @ApiOperation(value = "获取最新暂存")
//    public ResponseDTO<Object> getStorage(@RequestParam("bookGroup") String bookGroup){
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<NepuDraft> draftOp = draftService.getLastDraft(userId,ResearchTypeConst.BOOK+bookGroup);
//        if (!draftOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        NepuDraft draft = draftOp.get();
//        return ResponseDTO.succData(JsonUtil.string2Obj(draft.getFormJsonStr(),NepuBookAddDTO.class));
//    }
//
//    @GetMapping("books/storage/all")
//    @ApiOperation(value = "获取全部暂存")
//    public ResponseDTO<Object> getAllStorage(@RequestParam("bookGroup") String bookGroup){
//        Long userId = StpUtil.getLoginIdAsLong();
//        List<NepuDraft> drafts = draftService.getFormAllDrafts(userId,ResearchTypeConst.BOOK+bookGroup);
//        return ResponseDTO.succData(drafts);
//    }


    @PostMapping(value = "tmaterials")
    @ApiOperation(value = "新建记录",notes = "")
    public ResponseDTO<Object> saveOne(@RequestBody @Validated TMaterialCreateParams params){
        // 1. 获取操作人员ID
        String operator = StpUtil.getLoginIdAsString();
        // 2. 表单校验
        String errMsg = ValidUtil.formValid(params);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,errMsg);
        }

        String periodId = periodLoader.getPeriodId();
        // 3. 获取词典信息
        TMaterialDict dict = dictService.getOneUnwrap(params.getTmaterialDictId());
        // 4. 写入记录 并赋值最大工作量
        TMaterial tmaterial = new TMaterial();
        BeanUtil.copyProperties(params,tmaterial, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        // 修复图书工作量写入计算
        tmaterial.setWorkload( dict.getWorkloadStandard() * params.getWordsNumber());
        tmaterial.setPeriodId(periodId);
        tmaterial.setStatus(1);
        TMaterial saveRes=service.saveOne(tmaterial);
        // 5. 写入绑定文件信息 -- 修改为异步任务
        List<String> fileIds = params.getFileIds();

        return ResponseDTO.succData(saveRes);
    }

    @PutMapping(value = "tmaterials")
    @ApiOperation(value = "更新单条记录",notes = "")
    public ResponseDTO<Object> updateOne(@RequestBody @Validated TMaterialUpdateParams params){
        Optional<TMaterial> bookOp = service.getOne(params.getId());
        if (!bookOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        TMaterial tmaterial = bookOp.get();
        BeanUtil.copyProperties(params,tmaterial,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(service.updateOne(tmaterial));
    }

    @GetMapping(value = "tmaterials/{id}")
    @ApiOperation(value = "查询单条记录",notes = "")
    public ResponseDTO<TMaterial> getOne(@PathVariable("id") String id){
        Optional<TMaterial> entityOp = service.getOne(id);
        return entityOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(HttpStatus.NOT_FOUND));
    }

    @DeleteMapping(value = "tmaterials/{id}")
    @ApiOperation(value = "删除单条记录",notes = "")
    public ResponseDTO<Object> deleteOne(@PathVariable("id") String id){
        service.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }


    @GetMapping(value = {"tmaterials"})
    @ApiOperation(value = "查询全部",notes = "")
    public ResponseDTO<Object> getAll(TAwardQueryParams params){
        Sort sort;
        if(params.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, params.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, params.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(params.getPageNum() - 1 , params.getPageSize(), sort);

        TMaterial tmaterial = new TMaterial();
        BeanUtil.copyProperties(params,tmaterial, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<TMaterial> example = Example.of(tmaterial);
        return ResponseDTO.succData(service.getAll(pageable,example));

    }

//    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
//    @PutMapping("books/files")
//    @ApiOperation(value = "更新附件信息",notes = "")
//    public ResponseDTO<Object> updateFiles(@RequestBody @Validated FileUpdateDTO dto){
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<Object> bookOp = researchServiceCtl.getById(dto.getMapperId(),ResearchTypeConst.BOOK);
//        if (!bookOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        }
//        NepuBook book = (NepuBook) bookOp.get();
//        if (!userId.equals(book.getFirstAuthorId())){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"非负责人无法修改");
//        }
//        // 清理之前的附件信息
//        nepuResearchFileService.deleteEntityLink(book.getId());
//        // 写入新的附件信息
//        List<String> fileIds = dto.getFileIds();
//        nepuResearchFileService.batchBindFile(ResearchTypeConst.BOOK,book.getId(),fileIds);
//        // 返回操作信息
//        return ResponseDTO.succMsg("更新成功");
//    }


    @PutMapping("tmaterials/{id}/workload")
    @ApiOperation(value = "修改记录工作量")
    public ResponseDTO<Object> updateWorkload(@PathVariable("id") String id,@RequestParam("workload") Double workload){
        Optional<TMaterial> entityOp = service.getOne(id);
        if (!entityOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未找到对应课题记录");
        }
        TMaterial tmaterial = entityOp.get();
        String dictId = tmaterial.getTmaterialDictId();
        Optional<TMaterialDict> dictOp = dictService.getOne(dictId);
        if (!dictOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未找到课题关联词典记录");
        }
        tmaterial.setWorkload(workload);
        // 写入记录
        return ResponseDTO.succData(service.updateOne(tmaterial));
    }
}
